package com.hqq.mybatisTest.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory=null;

    //考虑到SqlSessionFactory最好只创建一次 所以放在静态代码块里
    static {
        //1-定义mybatis主配置文件 从类路径target/clasees开始
        String config = "mybatis.xml";
        //2读取config表示的文件
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(config);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //获取sqlSession对象的方法
    public static SqlSession getSqlSession(){

        SqlSession sqlSession = null;
        if (null != sqlSessionFactory){
            sqlSession = sqlSessionFactory.openSession();

        }

        return sqlSession;

    }
}
